package com.shenyue.nbtownlet.activity;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.databinding.DataBindingUtil;
import android.location.Location;
import android.os.Bundle;
import android.os.Handler;
import android.provider.Settings;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.SearchView;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.chanven.lib.cptr.PtrDefaultHandler;
import com.chanven.lib.cptr.PtrFrameLayout;
import com.chanven.lib.cptr.loadmore.OnLoadMoreListener;
import com.shenyue.nbtownlet.R;
import com.shenyue.nbtownlet.adapter.WaitTaskListViewAdapter;
import com.shenyue.nbtownlet.base.BaseActivity;
import com.shenyue.nbtownlet.databinding.ActivityWaitTaskBinding;
import com.shenyue.nbtownlet.event.BaseListener;
import com.shenyue.nbtownlet.location.BDLocationManager;
import com.shenyue.nbtownlet.model.AppLoginModel;
import com.shenyue.nbtownlet.model.AppTaskModel;
import com.shenyue.nbtownlet.model.DefaultModel;
import com.shenyue.nbtownlet.util.GpsUtil;
import com.shenyue.nbtownlet.util.MapDistance;
import com.shenyue.nbtownlet.util.NetWorkUtils;
import com.shenyue.nbtownlet.util.StringUtil;

import java.io.File;

/**
 * 待办任务
 */
public class WaitTaskActivity extends BaseActivity implements WaitTaskListViewAdapter.WaitTaskListItemClickListener {
    private ActivityWaitTaskBinding binding;
    private Context mContext;
    private WaitTaskListViewAdapter listViewAdapter;
    private int pageNo = 1, pageSize = 10;
    private Handler mHandler = new Handler();
    private MenuItem searchMenu;
    private SearchView searchView;
    private String type;
    private static final int TYPE_ACTION = 0x009;
    private BDLocationManager bdLocationManager = new BDLocationManager();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        binding = DataBindingUtil.setContentView(this, R.layout.activity_wait_task);
        setActionBar(true, getString(R.string.tv_wait_task));
        mContext = this;

        listViewAdapter = new WaitTaskListViewAdapter(mContext);
        binding.listView.setAdapter(listViewAdapter);
        listViewAdapter.setOnItemClickListener(this);

        binding.ptrClassicFrameLayout.setPtrHandler(new PtrDefaultHandler() {
            @Override
            public void onRefreshBegin(PtrFrameLayout frame) {
                if (!NetWorkUtils.isNetworkConnected(mContext)) {
                    binding.ptrClassicFrameLayout.refreshComplete();
                    showMsg(getString(R.string.no_network));
                    return;
                }
                query();
            }
        });

        binding.ptrClassicFrameLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void loadMore() {
                if (!NetWorkUtils.isNetworkConnected(mContext)) {
                    binding.ptrClassicFrameLayout.loadMoreComplete(false);
                    showMsg(getString(R.string.no_network));
                    return;
                }
                queryMore();
            }
        });
        binding.ptrClassicFrameLayout.disableWhenHorizontalMove(true);

        mHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                binding.ptrClassicFrameLayout.autoRefresh();
            }
        }, 32);

        updateLocation();
    }

    private void query() {
        listViewAdapter.clear();
        pageNo = 1;
        JSONObject param = new JSONObject();
        param.put("status", "0");
        param.put("title", searchView == null ? "" : searchView.getQuery().toString());
        param.put("type", StringUtil.getValue(type));
        param.put("userID", AppLoginModel.getIdentityId(mContext));
        param.put("pagenumber", pageNo);
        param.put("pagesize", pageSize);
        AppTaskModel.WaitList(mContext, param, new BaseListener() {
            @Override
            public void success(String val, String action) {
                binding.ptrClassicFrameLayout.refreshComplete();
                JSONObject data = JSON.parseObject(val);
                long count = data.getLong("count");
                JSONArray array = data.getJSONArray("data");
                binding.ptrClassicFrameLayout.setLoadMoreEnable(!(count < pageSize));
                listViewAdapter.addItems(array);
            }

            @Override
            public void error(String error, String action) {
                binding.ptrClassicFrameLayout.refreshComplete();
                showMsg(error);
            }
        });
    }

    private void queryMore() {
        pageNo += 1;
        JSONObject param = new JSONObject();
        param.put("status", "0");
        param.put("title", searchView == null ? "" : searchView.getQuery().toString());
        param.put("type", StringUtil.getValue(type));
        param.put("userID", AppLoginModel.getIdentityId(mContext));
        param.put("pagenumber", pageNo);
        param.put("pagesize", pageSize);
        AppTaskModel.WaitList(mContext, param, new BaseListener() {
            @Override
            public void success(String val, String action) {
                JSONObject data = JSON.parseObject(val);
                long count = data.getLong("count");
                JSONArray array = data.getJSONArray("data");
                binding.ptrClassicFrameLayout.loadMoreComplete(!(count < (pageNo * pageSize)));
                listViewAdapter.addItems(array);
            }

            @Override
            public void error(String error, String action) {
                binding.ptrClassicFrameLayout.loadMoreComplete(false);
                showMsg(error);
            }
        });
    }

    private void setSearchView() {
        if (this.searchView != null) {
            EditText searchPlate = (EditText) this.searchView.findViewById(android.support.v7.appcompat.R.id.search_src_text);
            if (searchPlate == null)
                return;
            searchPlate.setOnEditorActionListener(new TextView.OnEditorActionListener() {
                @Override
                public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                    if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                        binding.ptrClassicFrameLayout.autoRefresh();
                    }
                    return false;
                }
            });
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.wait_task_menu, menu);
        searchMenu = menu.findItem(R.id.action_search);
        searchView = (SearchView) searchMenu.getActionView();
        searchView.setQueryHint("请输入名称检索");
        setSearchView();
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        hideSearchView();
        switch (item.getItemId()) {
            case R.id.btn_all:
                type = null;
                binding.ptrClassicFrameLayout.autoRefresh();
                break;
            case R.id.btn_patrol_task:
                type = "2";
                binding.ptrClassicFrameLayout.autoRefresh();
                break;
            case R.id.btn_office_check:
                type = "1";
                binding.ptrClassicFrameLayout.autoRefresh();
                break;
            case R.id.btn_information_reports:
                type = "4";
                binding.ptrClassicFrameLayout.autoRefresh();
                break;
            case R.id.btn_notice:
                type = "3";
                binding.ptrClassicFrameLayout.autoRefresh();
                break;
            case R.id.btn_addressee_distribution:
                type = "5";
                binding.ptrClassicFrameLayout.autoRefresh();
                break;
        }
        return super.onOptionsItemSelected(item);
    }

    private void hideSearchView() {
        if (this.searchMenu != null)
            this.searchMenu.collapseActionView();
    }

    @Override
    public void onItemClick(int position) {
        if (!NetWorkUtils.isNetworkConnected(this)) {
            showMsg(getString(R.string.no_network));
            return;
        }
        JSONObject item = (JSONObject) listViewAdapter.getItem(position);
        String type = StringUtil.getValue(item.getString("type"));
        JSONObject flow = item.getJSONObject("flow");
        Bundle bundle = new Bundle();
        bundle.putString(DefaultModel.PAGE_DATA, flow.toString());
        if ("1".equals(type)) {
            Toast.makeText(mContext, "功能正在开发中...", Toast.LENGTH_LONG).show();
        } else if ("2".equals(type)) {
            toActivityForResult(WaitTaskDetailActivity.class, bundle, TYPE_ACTION);
        } else if ("3".equals(type)) {
            toActivityForResult(NoticeDetailActivity.class, bundle, TYPE_ACTION);
        } else if ("4".equals(type)) {
            toActivityForResult(InformationDistributionDetailActivity.class, bundle, TYPE_ACTION);
        } else if ("5".equals(type)) {
            toActivityForResult(AddresseeDistributionDetailActivity.class, bundle, TYPE_ACTION);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (resultCode == RESULT_OK && requestCode == TYPE_ACTION) {
            binding.ptrClassicFrameLayout.autoRefresh();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();

        if (!GpsUtil.isOPen(mContext)) {
            AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
            builder.setTitle("定位服务")
                    .setMessage("定位服务尚未打开，位置获取精度差，是否开启定位服务？")
                    .setPositiveButton("去开启", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            //跳转到设置页面让用户自己手动开启
                            Intent locationIntent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                            startActivity(locationIntent);
                        }
                    }).setNegativeButton("稍候再说", null);
            builder.create().show();
        } else {
            bdLocationManager.start(mContext);
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        bdLocationManager.stop();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        bdLocationManager.stop();
    }

    private void updateLocation() {
        mHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                Location location = bdLocationManager.getLocation();
                if (location != null) {
                    updateListUI(location);
                }
                updateLocation();
            }
        }, 2000);
    }

    private void updateListUI(Location location) {
        try {
            double longitude = Double.valueOf(StringUtil.getDoubleScale(location.getLongitude(), 8));
            double latitude = Double.valueOf(StringUtil.getDoubleScale(location.getLatitude(), 8));
            for (int i = 0, j = listViewAdapter.getCount(); i < j; i++) {
                JSONObject item = (JSONObject) listViewAdapter.getItem(i);
                if (StringUtil.isNull(item.getString("mapy")) || StringUtil.isNull(item.getString("mapx")))
                    continue;
                double mapy = item.getDoubleValue("mapy");
                double mapx = item.getDoubleValue("mapx");
                String distance = GpsUtil.getDistance(longitude, latitude, mapx, mapy);
                item.put("distance", "距离您约" + distance);
            }
            listViewAdapter.notifyDataSetChanged();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
